package com.util;

/**
 * Created by zhanghf on 2015/6/29.
 */
//import org.hibernate.HibernateException;
//import org.hibernate.Session;
//import org.hibernate.SessionFactory;
//import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.util.ThreadLocal;

//public class HibernateUtil {
//    private static SessionFactory sessionFactory;
//
//    /**
//     * @return 获取会话工厂
//     */
//    public static SessionFactory getSessionFactory()
//    {
//        //第一步:读取Hibernate的配置文件  hibernamte.cfg.xml文件
//        Configuration con = new Configuration().configure();
//        //第二步:创建服务注册构建器对象，通过配置对象中加载所有的配置信息
//        ServiceRegistryBuilder regbulider = new ServiceRegistryBuilder().applySettings(con.getProperties());
//        //创建注册服务
//        ServiceRegistry reg = regbulider.buildServiceRegistry();
//        //第三步:创建会话工厂
//        SessionFactory sessionFactory = con.buildSessionFactory(reg);
//        return sessionFactory;
//    }
//
//    /**
//     * @return 获取会话对象
//     */
//    public static Session getSession()
//    {
//        return getSessionFactory().openSession();
//    }
//}

import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.sql.Connection;
import org.apache.log4j.Logger;
import org.hibernate.jdbc.Work;

import java.io.File;

/**
 * Title:Hibernate工具类
 * 利用ThreadLocal 绑定 Hibernate 的session
 * @author
 * @version 1.0
 */

public class HibernateUtil {

    /**
     * Loger4j的logger
     */
    private static final Logger logger = Logger.getLogger(HibernateUtil.class);

    /**
     * 存储hibernate session的ThreadLocal
     */
    private static final ThreadLocal sessionThread = new ThreadLocal();

    /**
     * 存储事务的ThreadLocal
     */
    private static final ThreadLocal transactionThread = new ThreadLocal();

    /**
     * Hibernate 的 Session工厂
     */
    private static SessionFactory sessionFactory = null;

    /**
     * 初始化SessionFactory
     * @param
     */
    public static void initSessionFactory() {

        //第一步:读取Hibernate的配置文件  hibernamte.cfg.xml文件
        Configuration con = new Configuration().configure();
        //第二步:创建服务注册构建器对象，通过配置对象中加载所有的配置信息
        ServiceRegistryBuilder regbulider = new ServiceRegistryBuilder().applySettings(con.getProperties());
        //创建注册服务
        ServiceRegistry reg = regbulider.buildServiceRegistry();
        //第三步:创建会话工厂
        sessionFactory = con.buildSessionFactory(reg);
    }

     /**
     * 获取当前线程绑定的session
     * @return Session
     * @throws HibernateException
     */
    public static Session getSession() {
        Session s = (Session) sessionThread.get();
        if (s == null) {
            s = sessionFactory.openSession();
            sessionThread.set(s);
        }
        else {
            if (!s.isConnected()) {
                try {
                    s.close();
                } catch (HibernateException e) {
                    logger.warn("close session error:" + e.getMessage(), e);
                }
                s = sessionFactory.openSession();
                sessionThread.set(s);
            }
        }
        return s;
    }

    /**
     * 取得当前session的事务
     * @return Transaction
     */
    public static Transaction transaction() {
        Transaction transaction = (Transaction) transactionThread.get();
        if (transaction == null) {
            transaction = getSession().beginTransaction();
            transactionThread.set(transaction);
        }
        return transaction;
    }

    /**
     * 提交当前session的事务
     */
    public static void commitTransaction() {
        Transaction transaction = (Transaction) transactionThread.get();
        transactionThread.set(null);
        if (transaction != null)
            transaction.commit();
    }

    /**
     * 回滚当前session的事务
     */
    public static void rollbackTransaction() {
        Transaction tx = (Transaction) transactionThread.get();
        transactionThread.set(null);
        if (tx != null)
            tx.rollback();
    }

    /**
     * 关闭当前线程使用的session
     */
    public static void closeSession() {
        Session session = (Session) sessionThread.get();
        if (session != null) {
            session.clear();
            session.close();
            sessionThread.set(null);
        }
    }
}